// 这里封装首页模块相关的请求actionCreate

import { ApiResponse, Article, Channel } from '@/types/data'
import { RootAction, RootThunkAction } from '@/types/store'
import { getChannels, setChannels } from '@/utils/channels'
import http from '@/utils/request'
import { hasToken } from '@/utils/token'

// todo 获取用户频道
export function getUserChannelsActionCreate(): RootThunkAction {
  return async (dispatch) => {
    if (hasToken()) {
      // 登陆了, 发送请求获取自己的数据, 发请求操作自己的数据
      const res = await http.get<ApiResponse<{ channels: Channel[] }>>(
        '/user/channels'
      )
      console.log('登录了', res)

      dispatch({
        type: 'home/set_user_Channels',
        payload: res.data.data.channels,
      } as RootAction)
    } else {
      // 没登录, 也可以看首页, 发请求拿默认数据, 操作本地数据
      // 判断本地存储有无数据

      // 判断本地存储有无数据
      const userChannels = getChannels()
      if (userChannels.length > 0) {
        // 该设备已经在未登录的情况下,访问过网页, 本地有数据
        console.log('本地有数据了')

        dispatch({
          type: 'home/set_user_Channels',
          payload: userChannels,
        } as RootAction)
      } else {
        // 没有登录, 第一次访问网页
        // 发请求获取默认的数据, 存取到本地中, 为后期没有登录的时候使用
        const res = await http.get<ApiResponse<{ channels: Channel[] }>>(
          '/user/channels'
        )
        console.log('没有登录获取channels的数据', res)

        setChannels(res.data.data.channels)
        dispatch({
          type: 'home/set_user_Channels',
          payload: res.data.data.channels,
        } as RootAction)
      }
    }
  }
}

// todo 获取所有频道
export function getAllChannelsActionCreate(): RootThunkAction {
  return async (dispatch) => {
    const res = await http.get<ApiResponse<{ channels: Channel[] }>>(
      '/channels'
    )
    // console.log('all', res)

    dispatch({
      type: 'home/set_all_Channels',
      payload: res.data.data.channels,
    } as RootAction)
  }
}

// todo 请求添加频道
export function addChannelActionCreate(channel: Channel): RootThunkAction {
  return async (dispatch, getState) => {
    // 获取当前 Redux 中的“我的频道”数据
    const userChannels = getState().home.userChannels

    // 如果当前已登录，则通知服务端向 “我的频道” 新增频道
    if (hasToken()) {
      // 登录了, 操作的是接口中的频道数据
      await http.patch('/user/channels', {
        channels: [channel],
      })
    } else {
      // 如果未登录，则向本地缓存中保存新增的频道
      // 老的数据+channel
      setChannels([...userChannels, channel])
    }

    // 将最新的“我的频道”数据存入 Redux 中
    dispatch({
      type: 'home/set_user_Channels',
      payload: [...userChannels, channel],
    } as RootAction)
  }
}

// todo 删除指定频道
export function delChannelActionCreate(id: number): RootThunkAction {
  return async (dispatch, getState) => {
    const userChannels = getState().home.userChannels

    if (hasToken()) {
      // 操作自己的数据
      await http.delete('/user/channels' + id)
    } else {
      // 操作本地的数据
      const resChannels = userChannels.filter((item) => item.id !== id)
      setChannels(resChannels)
    }

    // 获取最新的用户频道
    dispatch(getUserChannelsActionCreate())
  }
}

// todo 获取频道下面的文章数据( 上拉加载)
export function getArticleListActionCreator(
  channel_id: number,
  timestamp: string
): RootThunkAction {
  return async (dispatch) => {
    const res = await http.get<
      ApiResponse<{
        pre_timestamp: string
        results: Article[]
      }>
    >('/articles', {
      params: {
        // 获取指定频道的文章列表
        channel_id,
        // 获取距离该时间最近的文章列表
        timestamp,
      },
    })
    console.log(res)
    // res.data.data.results
    const { pre_timestamp, results } = res.data.data
    dispatch({
      type: 'home/set_channel_articles',
      payload: {
        channel_id,
        timestamp: pre_timestamp,
        articles: results,
      },
    } as RootAction)
  }
}

//todo 下拉刷新
export function refreshArticleListActionCreate(
  channel_id: number,
  timestamp: string
): RootThunkAction {
  return async (dispatch) => {
    const res = await http.get<
      ApiResponse<{
        pre_timestamp: string
        results: Article[]
      }>
    >('/articles', {
      params: {
        channel_id,
        timestamp,
      },
    })

    const { pre_timestamp, results } = res.data.data

    dispatch({
      type: 'home/refresh_articles',
      payload: {
        channel_id,
        timestamp: pre_timestamp,
        articles: results,
      },
    } as RootAction)
  }
}
